package com.wangjie.simple;

/**
 * @author jieshao
 * @date 2022/5/31 13:15
 *
 * 1816. 截断句子
 */
public class Test17 {
    public static void main(String[] args) {
        String s = "Hello how are you Contestant";
        String res = truncateSentence(s, 5);
        System.out.println(res);
    }

    public static String truncateSentence(String s, int k) {
        int end = 0;
        int count = 0;
        for (int i = 1; i <= s.length(); i++) {
            if (i == s.length() || ' ' == s.charAt(i)) {
                count++;
                if (count == k) {
                    end = i;
                    break;
                }
            }
        }
        return s.substring(0, end);
    }
}